﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace B303Langf.Parser
{
   public abstract class ReflectiveTreeViewNode : ITreeViewNode
   {
      protected virtual string Value
      {
         get
         {
            return null;
         }
      }

      #region ITreeViewNode Members

      [TraverseIgnore]
      public virtual string Title
      {
         get
         {
            return GetType().Name + ( string.IsNullOrEmpty( Value ) ? string.Empty : " (" + Value + ")" );
         }
      }

      [TraverseIgnore]
      public virtual IEnumerable<ITreeViewNode> Children
      {
         get
         {
            var properties = GetType().GetProperties();
            foreach( var property in properties )
            {
               bool ignore = property.GetCustomAttributes( true ).Any( x => x is TraverseIgnoreAttribute );
               if( property.CanRead && !ignore )
               {
                  var obj = property.GetValue( this );
                  if( obj is ITreeViewNode )
                  {
                     var node = (ITreeViewNode) obj;
                     yield return node;
                  }
                  else if( obj is IEnumerable )
                  {
                     var enumerable = (IEnumerable) obj;
                     foreach( var child in enumerable )
                     {
                        if( child is ITreeViewNode )
                        {
                           var childNode = (ITreeViewNode) child;
                           yield return childNode;
                        }
                     }
                  }
               }
            }
         }
      }

      #endregion
   }
}
